import type { AxiosResponse } from 'axios'

import type { ResWrapper } from './common/commonApi'
import axios, { AxiosHeaders } from 'axios'
import { useLoginStore } from '@/stores/loginStore'
import { ErrType } from './common/commonApi'

if (import.meta.env.VITE_API_BASE_URL) {
  axios.defaults.baseURL = import.meta.env.VITE_API_BASE_URL
}

axios.interceptors.request.use(
  (config) => {
    if (config.url?.startsWith('http')) {
      return config
    }
    if (!config.headers) {
      config.headers = new AxiosHeaders()
    }
    const token = useLoginStore().user.token
    if (token) {
      config.headers.Authorization = `Bearer ${token}`
    }
    config.headers['app-type'] = 'MANAGE'
    config.headers['app-ver'] = import.meta.env.VITE_APP_VERSION
    return config
  },
  (error) => {
    // do something
    return Promise.reject(error)
  },
)
// add response interceptors
axios.interceptors.response.use(
  async (response) => {
    if (response.config.responseType === 'blob') {
      const blob = response.data as Blob
      if (blob.type === 'application/json') {
        const text = await blob.text()
        handleError(response, JSON.parse(text))
        return Promise.reject(text)
      }
      else {
        downloadFile(response, blob)
      }
      return response
    }
    const res = response.data
    if (!Object.prototype.hasOwnProperty.call(res, 'success')) {
      return response
    }
    if (!res.success) {
      handleError(response, res)
      return Promise.reject(res)
    }
    return res
  },
  (error) => {
    ElMessage({
      type: 'error',
      message:
        (ErrType as Record<string, string>)[error.code as string]
        || 'Request Error',
      grouping: true,
    })
    return Promise.reject(error)
  },
)
let reLoginConfirm = false

function handleError(response: AxiosResponse, res: ResWrapper) {
  if ([401].includes(res.errCode)) {
    if (!response.config.url?.includes('/login/info') && !reLoginConfirm) {
      reLoginConfirm = true
      ElMessageBox.confirm('是否重新登录', 'Warning')
        .then(async () => {
          await useLoginStore().logout()
          reLoginConfirm = false
          window.location.reload()
        })
        .catch(() => reLoginConfirm = false)
    }
  }
  else {
    ElMessage({
      type: 'error',
      message: res.errMsg || 'Error',
      grouping: true,
    })
  }
}

function downloadFile(response: AxiosResponse, blob: Blob) {
  const headers = response.headers // 下载后文件名
  let filename = headers['content-disposition']
  filename = decodeURI(filename.split(';')[1].split('filename=')[1])

  const downloadElement = document.createElement('a')
  const href = URL.createObjectURL(blob) // 创建下载的链接
  downloadElement.href = href
  downloadElement.download = filename
  document.body.appendChild(downloadElement)
  downloadElement.click() // 点击下载
  document.body.removeChild(downloadElement) // 下载完成移除元素
  URL.revokeObjectURL(href) // 释放掉blob对象
}
